﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OAuth;
using YammerAPI;

namespace YammerWM6
{
    public partial class frmMessages : Form
    {
        const int DISPLAYED_MESSAGES = 10;
        int refreshInterval = 60 * 1000;

        static string ConsumerKey
        {
            get { return "sr9T2jaYHifc5f3HA3hWTA"; }
        }

        static string ConsumerSecret
        {
            get { return "RqIUFeOAHhae9fWmsmZfKeeifJHIg4HxCvuvvWMiDEs"; }
        }

        internal static IAccessTokenStorage TokenStorage = new RegistryTokenStorage();

        YammerAPI.ApiWrapper api;
        ucShortMessage[] messageContrals;
        frmSendMessage sendDialog = null;
        string lastReceivedId = string.Empty;

        public frmMessages()
        {
            InitializeComponent();
            messageContrals = new ucShortMessage[DISPLAYED_MESSAGES];
            for (int i = 0; i < DISPLAYED_MESSAGES; i++)
            {
                messageContrals[i] = new ucShortMessage()
                {
                    Height = 118,
                    Dock = DockStyle.Top
                };
                pnlMessages.Controls.Add(messageContrals[i]);
            }

            // set up interval update
            updateIntervalTimer.Enabled = false;
            updateIntervalTimer.Interval = refreshInterval;
            mnuUpdateByInterval.Checked = false;
            updateIntervalTimer.Tick += new EventHandler(updateIntervalTimer_Tick);
        }

        void updateIntervalTimer_Tick(object sender, EventArgs e)
        {
            LoadMessages();
        }

        private void frmMessages_Load( object sender, EventArgs e )
        {
            api = new YammerAPI.ApiWrapper(
                ConsumerKey,
                ConsumerSecret,
                TokenStorage,
                str =>
                    {
                        using(var frm = new frmAuth())
                        {
                            frm.Url = WebUtils.UrlShorteners.rim.Instance.Shorten(str);
                            frm.ShowDialog();
                            return frm.UserCode;
                        }
                    });
            api.StartSession(false);
        }

        private void mnuQuit_Click( object sender, EventArgs e )
        {
            this.Close();
        }

        private void mnuReset_Click( object sender, EventArgs e )
        {
            api.StartSession(true);
        }

        private void LoadMessages()
        {
            try
            {
                string newLastId = string.Empty;
                var i = -1;
                foreach(var msg in (from m in (api.GetFollowingMessages().Take(DISPLAYED_MESSAGES).Reverse<Message>())
                                    select new
                                    {
                                        Username = (from user in m.References.Users
                                                    where user.Id == m.SenderId
                                                    select user.FullName).First(),
                                        shortName = (from user in m.References.Users
                                                     where user.Id == m.SenderId
                                                     select user.Name).First(),
                                        Message = m.Body.Plain,
                                        Time = m.CreatedAt,
                                        Id = m.Id
                                    }))
                {
                    var msgControl = messageContrals[++i];
                    msgControl.From = string.Format(
                        "{0} -- {1}",
                        msg.Username,
                        msg.shortName);
                    msgControl.Date = msg.Time;
                    msgControl.Msg = msg.Message;
                    newLastId = msg.Id;
                }
                messageContrals[0].Focus();

                if(newLastId != lastReceivedId && mnuUpdateByInterval.Checked)
                {
                    notification.Visible = true;
                }
                lastReceivedId = newLastId;
            }
            catch(Exception ex)
            {
                var msg = string.Format(
                    "{0}\n{1}",
                    ex.Message,
                    "try to reset the application");
                MessageBox.Show(msg);
            }
        }

        private void mnuRefresh_Click( object sender, EventArgs e )
        {
            LoadMessages();
        }

        private void mnuRunTests_Click( object sender, EventArgs e )
        {
            TestRunner.RunTests();
        }

        private void mnuNewMsg_Click( object sender, EventArgs e )
        {
            if (sendDialog == null)
                sendDialog = new frmSendMessage();
            sendDialog.SetSendToAll();
            if (sendDialog.ShowDialog() == DialogResult.OK)
            {
                api.PostMessage(
                    sendDialog.txtMsg.Text,
                    null);
            }
        }

        private void mnuUpdateByInterval_Click(object sender, EventArgs e)
        {
            mnuUpdateByInterval.Checked = !mnuUpdateByInterval.Checked;
            if(mnuUpdateByInterval.Checked)
            {
                updateIntervalTimer.Enabled = true;
            }
            else
            {
                updateIntervalTimer.Enabled = false;
            }
        }

    }
}